package com.xinzhidi.web.netty.utils;

/***
 * @author cx
 * @date 2023/5/29 15:04
 */
public class MbusProtocolParser {

    public static void main(String[] args) {
        // 示例主站发送帧
        String mainStationFrame = "fefefe6840aaaaaaaaaaaaaa03030a81371616";
        // 示例从站发送帧
        String slaveStationFrame = "fefefe684078563412000000830c0a81370000785634120000001016";

        // 解析主站发送帧
        parseFrame(mainStationFrame);

        // 解析从站发送帧
        parseFrame(slaveStationFrame);
    }

    private static void parseFrame(String frame) {
        // 解析帧起始符
        String startSymbol = frame.substring(0, 8);

        // 解析设备类型
        String deviceType = frame.substring(8, 10);

        // 解析设备地址
        String deviceAddress = frame.substring(10, 24);

        // 解析控制码
        String controlCode = frame.substring(24, 26);

        // 解析数据域长度
        String dataLength = frame.substring(26, 28);

        // 解析数据标识
        String dataIdentifier = frame.substring(28, 30);

        // 解析帧序列号
        String sequenceNumber = frame.substring(30, 32);

        // 解析校验和
        String checksum = frame.substring(frame.length() - 4, frame.length() - 2);

        // 解析结束符
        String endSymbol = frame.substring(frame.length() - 2);

        // 输出解析结果
        System.out.println("帧起始符: " + startSymbol);
        System.out.println("设备类型: " + deviceType);
        System.out.println("设备地址: " + deviceAddress);
        System.out.println("控制码: " + controlCode);
        System.out.println("数据域长度: " + dataLength);
        System.out.println("数据标识: " + dataIdentifier);
        System.out.println("帧序列号: " + sequenceNumber);
        System.out.println("校验和: " + checksum);
        System.out.println("结束符: " + endSymbol);
        System.out.println("---------------------");
    }

}
